package com.microsoft.mcp.sample.client;

import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.http.HttpMcpTransport;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.openaiofficial.OpenAiOfficialChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolProvider;

import java.time.Duration;
import java.util.List;

/**
 * 基于 langchain4j 的 mcp client(集成模型调用 mcp server)
 */
public class LangChain4jClient {
  public static void main(String[] args) throws Exception {
    // 模型定义
    ChatLanguageModel model = OpenAiOfficialChatModel.builder()
        .baseUrl("https://api.siliconflow.cn/v1")
        .modelName("Qwen/Qwen3-8B")
        .apiKey("sk-qrcxmqxlyibljfqmkzyvdjhconjtywptojkkmujepxzniobj")
        .timeout(Duration.ofSeconds(60))
        .build();

    // 创建 MCP 通道连接 MCP server
    McpTransport transport = new HttpMcpTransport.Builder()
        .sseUrl("http://localhost:8080/sse")
        .timeout(Duration.ofSeconds(60))
        .logRequests(true)
        .logResponses(true)
        .build();

    // 创建 MCP client
    McpClient mcpClient = new DefaultMcpClient.Builder()
        .transport(transport)
        .build();

    // 创建 tool provider 自动发现 MCP tools
    ToolProvider toolProvider = McpToolProvider.builder()
        .mcpClients(List.of(mcpClient))
        .build();

    // 配置 AI Service 包含 LLM 及 tools
    Bot bot = AiServices.builder(Bot.class)
        .chatLanguageModel(model)
        .toolProvider(toolProvider)
        .build();

    // 自然语言触发模型调用工具
    try {
      String response = bot.chat("使用计算服务，计算 24.5 和 17.3 的和");
      System.out.println(response);

      response = bot.chat("144 的平方根是多少？");
      System.out.println(response);

      response = bot.chat("展示计算服务的帮助信息");
      System.out.println(response);
    } finally {
      mcpClient.close();
    }
  }

  // 创建一个 Bot 接口类，用于自然语言交互
  public interface Bot {
    String chat(String prompt);
  }

}
